import React from 'react';
import {injectIntl} from './intl';
import PropTypes from 'prop-types';
import DescriptionList from 'ant-design-pro/lib/DescriptionList';
import {Button, Form, Row, Col, Card, Spin, message, Modal, Collapse, Divider, Popconfirm} from 'antd';
import routes from './routes';
import {FORM_OPTIONS, PAGE} from '../constants';
import {PERMISSION} from './constants';
import styles from './style.css';
import Return from '../common/Return';
import {validateAdd} from './utils';
import DealerSelectPanel from '../common/DealerSelect/SelectEdit';
import PackingSelectPanel from './PackingSelectPanel';
import DetailTable from './DetailTable';
import {packingType} from '../Enum';
import {conventEnumValueToString, formatAmount} from '../utils';
const FormItem = Form.Item;
const {Description} = DescriptionList;
const EMPTY_ARRAY = [];

const Panel = Collapse.Panel;
export class Add extends React.PureComponent {
    state = {
        loading: false,
        hasOperat: false,
        isValidate: false,
        showPanel: false,
        tableLoading: false,
    };

    componentDidMount() {
        this.ismounted = true;
    }

    componentWillUnmount() {
        this.ismounted = false;
        this.props.onUmount();
    }

    handleFilterChange = (value, name) => {
        if(!this.state.hasOperat)
            this.setState({
                hasOperat: true
            });
        this.props.onConditionsChange(name, value);
    };

    showPanel = () => {
        this.setState({
            showPanel: !this.state.showPanel
        });
    }
    onClickAdd = () => {
        if(!this.state.hasOperat)
            this.setState({
                hasOperat: true
            });
        if(!this.props.conditions.dealerId)
            return message.warn(this.props.intl.formatMessage({
                id: 'queryPanel.message.dealerId',
                defaultMessage: '请先选择总代'
            }));
        this.setState({
            showPanel: true
        });
    }

    onSelectPacking = data => {
        this.setState({
            showPanel: false
        });
        if(data.length)
            this.props.onSelectDetails(data);
    }

    onClickDelete = e => {
        e.stopPropagation();
        const {id} = e.target.dataset;
        if(this.state.currentPanelId === id)
            this.setState({currentPanelId: ''});
        this.props.onDeleteDetail(id);
    };
    
    onSubmit = () => {
        const result = validateAdd(this.props.conditions);
        if(result) {
            this.setState({
                isValidate: true,
            });
            return message.warn(result);
        }
        this.setState({
            loading: true
        });
        this.props.onSubmit().then(success => {
            if(this.ismounted && !success)
                this.setState({
                    loading: false
                });
        });
    };

    onChangeCollapse = key => {
        const {details = []} = this.props.conditions;
        const {packingListDetails = []} = details.find(item => item.packingListId === key) || {};
        this.setState({
            currentPanelId: key
        });
        if(key && !packingListDetails.length) {
            this.setState({tableLoading: true});
            return this.props.onSearchPacking(key).then(res => {
                this.setState({tableLoading: false});
            });
        }
    }
    onDeleteAll = () => {
        this.props.onDeleteAll();
        this.setState({currentPanelId: ''});
    }
    render() {
        const {details = []} = this.props.conditions;
        const dealerInfo = this.props.conditions.dealerId ? {
            id: this.props.conditions.dealerId,
            code: this.props.conditions.dealerCode,
            name: this.props.conditions.dealerName
        } : null;
        let totalNumber = 0;
        let totalV = 0;
        if(details) {
            totalNumber = details.length;
            details.forEach(d => {
                totalV += (d.volume);
            });
        }
        
        const packingPanel = details.map(p => {
            const header = (
                <Row>
                    <Col span={22} className={styles.edit}>
                        <strong>{p.packingCode}</strong>
                        <Divider type="vertical" />
                        {`${this.props.intl.formatMessage({
                            id: 'addWorkItem.info.workKind',
                            defaultMessage: '包装类型/规格'
                        })}: ${conventEnumValueToString(packingType, p.packingType)} / ${p.container}`}
                    </Col>
                    <Col span={2} className={`col-align-right ${styles.collapseBtn}`}>
                        {<a data-id={p.packingListId} onClick={this.onClickDelete}>{this.props.intl.formatMessage({
                            id: 'addWorkItem.workItems.deleteBtn',
                            defaultMessage: '删除'
                        })}</a>}
                    </Col>
                </Row>
            );
            const dataSource = p.packingListDetails || EMPTY_ARRAY;
            return (
                <Panel key={p.packingListId} header={header} >
                    <Row className="form-standard">
                        <Col {...FORM_OPTIONS.col}>
                            <FormItem
                                label={this.props.intl.formatMessage({
                                    id: 'add.form.length',
                                    defaultMessage: '长度（mm）'
                                })}
                                {...FORM_OPTIONS.item}>
                                <span className="value-font">{p.length}</span>
                            </FormItem>
                        </Col>
                        <Col {...FORM_OPTIONS.col}>
                            <FormItem
                                label={this.props.intl.formatMessage({
                                    id: 'add.form.width',
                                    defaultMessage: '宽度（mm）'
                                })}
                                {...FORM_OPTIONS.item}>
                                <span className="value-font">{p.width}</span>
                            </FormItem>
                        </Col>
                        <Col {...FORM_OPTIONS.col}>
                            <FormItem
                                label={this.props.intl.formatMessage({
                                    id: 'add.form.height',
                                    defaultMessage: '高度（mm）'
                                })}
                                {...FORM_OPTIONS.item}>
                                <span className="value-font">{p.height}</span>
                            </FormItem>
                        </Col>
                        <Col {...FORM_OPTIONS.col}>
                            <FormItem
                                label={this.props.intl.formatMessage({
                                    id: 'add.form.volume',
                                    defaultMessage: '体积（m³）'
                                })}
                                {...FORM_OPTIONS.item}>
                                <span className="value-font">{p.volume}</span>
                            </FormItem>
                        </Col>
                        <Col {...FORM_OPTIONS.col}>
                            <FormItem
                                label={this.props.intl.formatMessage({
                                    id: 'add.form.netWeight',
                                    defaultMessage: '净重（kg）'
                                })}
                                {...FORM_OPTIONS.item}>
                                <span className="value-font">{p.netWeight}</span>
                            </FormItem>
                        </Col>
                        <Col {...FORM_OPTIONS.col}>
                            <FormItem
                                label={this.props.intl.formatMessage({
                                    id: 'add.form.grossWeight',
                                    defaultMessage: '毛重（kg）'
                                })}
                                {...FORM_OPTIONS.item}>
                                <span className="value-font">{p.grossWeight}</span>
                            </FormItem>
                        </Col>
                    </Row>
                    <DetailTable data={dataSource} loading={this.state.tableLoading} />
                </Panel>
            );
        });

        const currentSelectRowKeys = details.map(item => item.packingListId);
        return (
            <div className={styles.detail}>
                <Modal
                    title={this.props.intl.formatMessage({
                        id: 'add.stock.modal.title',
                        defaultMessage: '备件包装箱单查询'
                    })}
                    width="80%"
                    maskClosable={false}
                    footer={null}
                    wrapClassName={styles.dataSelectModal}
                    destroyOnClose={true}
                    visible={this.state.showPanel}
                    onCancel={this.showPanel}>
                    <PackingSelectPanel
                        isCabinet={this.props.isCabinet}
                        dealerId={this.props.conditions.dealerId}
                        currentSelectRowKeys={currentSelectRowKeys}
                        onSelect={this.onSelectPacking} />
                </Modal>
                <Spin spinning={this.state.loading}>
                    <Form className="form-standard">
                        <Card
                            title={this.props.intl.formatMessage({
                                id: 'add.card.title',
                                defaultMessage: '排柜单信息'
                            })}>
                            <Row>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem
                                        label={this.props.intl.formatMessage({
                                            id: 'queryPanel.form.dealerId',
                                            defaultMessage: '总代'
                                        })}
                                        {...FORM_OPTIONS.item}>
                                        <DealerSelectPanel
                                            value={dealerInfo}
                                            onSelect={this.props.onSelectDealer} />
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem
                                        label={this.props.intl.formatMessage({
                                            id: 'add.form.country',
                                            defaultMessage: '国家/地区'
                                        })}
                                        {...FORM_OPTIONS.item}>
                                        <span className="value-font">{this.props.conditions.country}</span>
                                    </FormItem>
                                </Col>
                            </Row>
                        </Card>
                        <Card
                            extra={<span className={styles.optionBtn}>
                                <Button key="addBtn" size="small" onClick={this.onClickAdd}>
                                    {this.props.intl.formatMessage({
                                        id: 'add.form.addBtn',
                                        defaultMessage: '新增'
                                    })}
                                </Button>
                                {details.length ? (<Popconfirm
                                    placement="top"
                                    key="deleteAll"
                                    onConfirm={this.onDeleteAll}
                                    title={this.props.intl.formatMessage({
                                        id: 'add.popconfirm.delete.message',
                                        defaultMessage: '是否确认清空?'
                                    })}
                                    okText={this.props.intl.formatMessage({
                                        id: 'add.popconfirm.confirm',
                                        defaultMessage: '确认'
                                    })}
                                    cancelText={this.props.intl.formatMessage({
                                        id: 'add.popconfirm.cancel',
                                        defaultMessage: '取消'
                                    })}>
                                    <Button size="small" key="clearBtn">
                                        {this.props.intl.formatMessage({
                                            id: 'add.materials.clearBtn',
                                            defaultMessage: '清空'
                                        })}
                                    </Button>
                                </Popconfirm>)
                                    : (
                                        <Button size="small" key="clearBtn">
                                            {this.props.intl.formatMessage({
                                                id: 'add.materials.clearBtn',
                                                defaultMessage: '清空'
                                            })}
                                        </Button>
                                    )}
                            </span>}
                            title={this.props.intl.formatMessage({
                                id: 'add.details.title',
                                defaultMessage: '排柜单清单'
                            })}
                            bordered={false}>
                            <Collapse accordion activeKey={this.state.currentPanelId} onChange={this.onChangeCollapse}>
                                {packingPanel}
                            </Collapse>
                            <DescriptionList style={{marginTop: '20px'}}>
                                <Description term={this.props.intl.formatMessage({
                                    id: 'add.operation.totalNumber',
                                    defaultMessage: '总包装数'
                                })}>{totalNumber}
                                </Description>
                                <Description term={this.props.intl.formatMessage({
                                    id: 'add.operation.totalV',
                                    defaultMessage: '总体积数'
                                })}>{formatAmount(totalV, 3)}
                                </Description>
                            </DescriptionList>
                        </Card>
                        {this.props.submitable && (
                            <Card type="inner">
                                <Row>
                                    <Col className="col-align-right">
                                        <Button
                                            key="submit"
                                            type="primary"
                                            loading={this.state.loading}
                                            onClick={this.onSubmit}>
                                            {this.props.intl.formatMessage({
                                                id: 'add.btn.submit',
                                                defaultMessage: '保存'
                                            })}
                                        </Button>
                                    </Col>
                                </Row>
                            </Card>
                        )}
                    </Form>
                </Spin>
                <div className="page-toolbar">
                    <Return
                        disabled={this.state.loading}
                        showWarning={this.state.hasOperat}
                        onConfirm={this.props.onCancel} />
                </div>
            </div>
        );
    }
}
Add.propTypes = {
    conditions: PropTypes.object.isRequired,
    submitable: PropTypes.bool.isRequired,
    onCancel: PropTypes.func.isRequired,
    onConditionsChange: PropTypes.func.isRequired,
    onUmount: PropTypes.func.isRequired,
    id: PropTypes.string,
    intl: PropTypes.object,
};
import {connect} from 'react-redux';
import {
    saveSubmitCondition,
    clearData,
    tableSearch,
    deleteAllDetail,
    selectPacking,
    deleteDetail,
    selectCountry,
    onClickSubmit,
    getPackingDetail,
} from './actions';
import {createSelector} from 'reselect';
import selectorFactory from 'Shared/utils/immutableToJsSelectorFactory';

const getSubmitData = selectorFactory(['page', 'appState', 'submitData']);

const getPermissions = createSelector(
    state => state.getIn(['page', 'domainData', 'permission', 'data']),
    (state, ownProps) => ownProps.isCabinet,
    (permissions, isCabinet) => {
        const data = permissions.toJS();
        return isCabinet ? data.includes(PERMISSION.reject) : data.includes(PERMISSION.apply);
    }
);
const mapStateToProps = (state, ownProps) => ({
    id: ownProps.id,
    isCabinet: Boolean(ownProps.isCabinet),
    submitable: getPermissions(state, ownProps),
    conditions: getSubmitData(state),
});

const mapDispatchToProps = (dispatch, ownProps) => ({
    onConditionsChange: (name, value) => dispatch(saveSubmitCondition(name, value)),
    onSubmit: () =>
        dispatch(onClickSubmit(ownProps.isCabinet)).then(res => {
            if(res.ok) {
                dispatch(tableSearch({
                    pageIndex: PAGE.index
                }));
                ownProps.history.push(routes.query.url());
            }
            return res.ok;
        }),
    onCancel: () => {
        ownProps.history.push(routes.query.url());
    },
    onUmount: () => dispatch(clearData()),
    onDeleteAll: () => dispatch(deleteAllDetail()),
    onDeleteDetail: id => dispatch(deleteDetail(id)),
    onSelectDealer: data => dispatch(selectCountry(data)),
    onSelectDetails: data => dispatch(selectPacking(data)),
    onSearchPacking: id => dispatch(getPackingDetail(id)),
});

export default connect(
    mapStateToProps,
    mapDispatchToProps
)(injectIntl(Add));
